<?php

namespace app\common\library\wechat;


/**
 * 小程序二维码
 * Class WxQrcode
 * @package app\common\library\wechat
 */
class WxQrcode extends WxBase
{

    // 微信支付配置
    private $config;

    /**
     * 构造函数
     * WxPay constructor.
     * @param $config
     */
    public function __construct($config = false)
    {
        parent::__construct();
        $this->config = $config;
        $this->config !== false && $this->setConfig($this->config['app_id'], $this->config['app_secret']);
    }
    
    
    /**
     * @return mixed
     */
    protected function getAccessToken()
    {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appId}&secret={$this->appSecret}";
        $result = $this->get($url);
        return json_decode($result,true)['access_token'];
    }

    

    /**
     * 获取小程序码
     * @param $scene
     * @param null $page
     * @param int $width
     * @return mixed
     * @throws BaseException
     */
    public function getQrcode($filename ,$scene, $page = null, $width = 430)
    {
        // 微信接口url
        $access_token = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$access_token}";
        // 构建请求
        $data = compact('scene', 'width');
        !is_null($page) && $data['page'] = $page;
        // 返回结果
        $result = $this->post($url, json_encode($data, JSON_UNESCAPED_UNICODE));

        if (!strpos($result, 'errcode')) {
            file_put_contents($filename, $result);
            return true;
        }
        $data = json_decode($result, true);

        $error = '小程序码获取失败 ' . $data['errmsg'];
        if ($data['errcode'] == 41030) {
            $error = '小程序页面不存在，请先发布上线后再生成';
        }
        return false;
    }

}